<template>
  <div class="overflow-x-auto">
    <!-- 将加载状态移到表格外部 -->
    <!-- <div
      v-if="scoreList.length === 0"
      class="flex justify-center items-center py-10"
    >
      <span class="loading spinning-spinner text-primary mt-40 w-1/15"></span>
    </div> -->
    <Loading v-show="isLoading"></Loading>
    <table class="table table-lg" v-show="!isLoading">
      <thead>
        <tr>
          <th>Name</th>
          <th>Class</th>
          <th>Subject</th>
          <th>Semester</th>
          <th>Score</th>
        </tr>
      </thead>
      <tbody>
        <ScoreListItem
          v-for="scoreItem in filterScoreListByPage"
          :key="scoreItem.id"
          :scoreItem="scoreItem"
          :currentStudent="
            isStudent
              ? personStudent
              : studentList.find(
                  (student) => student.student_id === scoreItem.student_id
                )
          "
        />
      </tbody>
    </table>
  </div>
  <Pagination :currentPage :pageCount />
</template>

<script setup>
import { getUserId } from "@/ultils/tokenHelper";
import ScoreListItem from "./ScoreListItem.vue";
import { useUserStore } from "@/stores/user";
import { getScoreList } from "@/services/ApiScore";
import { getStudentList } from "@/services/ApiStudent";

import { ref, onMounted, computed, watch } from "vue";

import Loading from "@/ui/Loading.vue";
import { storeToRefs } from "pinia";
import { useSearchStore } from "@/stores/search";
import Pagination from "@/ui/Pagination.vue";
import { getConfig } from "@/ultils/configHelper";

import { useRouter, useRoute } from "vue-router";

const route = useRoute();
const router = useRouter();

const userStore = useUserStore();
const { isStudent } = storeToRefs(userStore);

const searchStore = useSearchStore();
const { scoreSearchCondition } = storeToRefs(searchStore);

const isLoading = ref(true);

const currentPage = ref(route.query.page || 1);
const pageSize = getConfig("PAGE_SIZE");
const pageCount = computed(() =>
  Math.ceil(filterScoreList.value.length / pageSize)
);

const scoreList = ref([]);
const studentList = ref([]);
const personStudent = ref(null);

// const filterScoreList = computed(() => {
//   return scoreList.value.filter((scoreItem) =>
//     studentList.value
//       .map((student) => student.student_id)
//       .includes(scoreItem.student_id)
//   );
// });

//钩子

const filterScoreListByPage = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize;
  return filterScoreListBySearch.value.slice(
    startIndex,
    startIndex + parseInt(pageSize)
  );
});

const filterScoreList = computed(() => {
  if (!Array.isArray(scoreList.value) || !Array.isArray(studentList.value)) {
    return [];
  }

  const userId = getUserId();
  // 优化性能：先提取学生ID数组
  const studentIds = studentList.value.map(
    (student) => student.student_id || student.id
  );

  if (!isStudent.value) {
    return scoreList.value.filter((scoreItem) =>
      studentIds.includes(scoreItem.student_id)
    );
  }
  return scoreList.value.filter((scoreItem) => scoreItem.student_id === userId);
});

watch(
  () => currentPage.value,
  () => {
    router.push({ query: { page: currentPage.value } });
  }
);
watch(
  () => route.query.page,
  (page) => {
    currentPage.value = page;
  }
);

onMounted(async () => {
  router.push({ query: { page: currentPage.value } });

  isLoading.value = true;
  scoreList.value = await getScoreList();
  // console.log(scoreList.value);
  //用id查出姓名和班级
  // scoreList.value.forEach(async (item) => {
  //   const student = await fetchDataById("student", item.student_id);
  //   if (student) {
  //     item.name = student.name;
  //     item.class = student.class;
  //     item.grade = student.grade;
  //   }
  // });
  // console.log(scoreList.value);
  const userId = getUserId();

  studentList.value = await getStudentList(userId);

  // console.log(studentList.value[0].name);
  // console.log(filterScoreList.value);
  isLoading.value = false;
});

const filterScoreListBySearch = computed(() => {
  return filterScoreList.value.filter((scoreItem) => {
    const scoreInfoJSON = JSON.stringify([
      scoreItem.subject.toLowerCase(),
      scoreItem.semester_year,
      scoreItem.semester_season.toLowerCase(),
      scoreItem.score,
    ]);

    for (const condition of scoreSearchCondition.value) {
      if (!scoreInfoJSON.includes(condition)) {
        return false;
      }
    }
    return true;
  });
});
</script>
